/**
 * Copyright (C) 2015~2050 by foolstudio. All rights reserved.
 *
 * 本源文件中代码不经允许，不得用于商业用途，作者保留所有权。
 *
 * 作者：汪永松
 *
 * 电子邮箱：foolstudio@qq.com
 *
 */

package com.foolstudio.VehicleNumDemo.activities;

import java.util.logging.Level;
import java.util.logging.Logger;

import com.wintone.plate.FreePlatePackage;
import com.wintone.plate.Package;
import com.wintone.plateid.PlateIDAPI;
import com.wintone.plateid.TH_PlateIDCfg;
import com.foolstudio.VehicleNumDemo.IDef;
import com.foolstudio.VehicleNumDemo.R;
import com.foolstudio.VehicleNumDemo.RecognizeThread;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Intent;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageView;
import android.widget.TextView;

public class MainActivity extends Activity implements OnClickListener {

	private Handler mMsgHandler = null;
	//
	private TextView tv = null;
	//
	private ImageView mBtnCapture = null;

	@SuppressLint("HandlerLeak")
	@Override
	protected void onCreate(Bundle savedInstanceState) {

		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);

		tv = (TextView)findViewById(R.id.textView1);
		tv.setText("正在初始化，请稍候……");
		tv.setTextColor(Color.BLUE);

		//设置包名
		FreePlatePackage.FreePlatePackageName = "com.wintone.plateid.free"; //getPackageName();
		//初始化车牌识别SDK，包名必须保证为：com.wintone.plateid.free
		TH_PlateIDCfg cfg = new TH_PlateIDCfg();
		Object obj = new Package();
		int result = PlateIDAPI.TH_InitPlateIDSDK(cfg, (Package)obj);

		//获取按钮控件
		mBtnCapture = (ImageView)findViewById(R.id.btn_capture);

		Logger.getLogger(IDef.App_Tag).log(Level.WARNING, "Initialized PlateIDSDK v"+PlateIDAPI.TH_GetVersion()+" 结果代码: " + result);
		if(result != 0) {

			tv.setText("抱歉：初始化车牌识别库失败，错误代码："+result);
			tv.setTextColor(Color.RED);
			//隐藏点击按钮
			mBtnCapture.setVisibility(View.INVISIBLE);
			return;
		} else {
			tv.setText("");
			tv.setTextColor(Color.BLACK);
		}

		//并设置点击侦听
		mBtnCapture.setOnClickListener(this);

		//初始化主线程消息队列处理器接口
		mMsgHandler = new Handler() {
			@Override
			public void handleMessage(Message msg) {
				if(msg.what == IDef.Msg_Recognized_Finished) {
					recognizedFinished(msg.getData());
				}
			}
		};
	}

	@Override
	protected void onDestroy() {

		PlateIDAPI.TH_UninitPlateIDSDK();
		Logger.getLogger(IDef.App_Tag).log(Level.WARNING, "Uninitialized PlateIDSDK");

		// TODO Auto-generated method stub
		super.onDestroy();
	}

	@Override
	public void onClick(View v) {
		if(v.getId() == R.id.btn_capture) {
			Intent intent = new Intent(this, CaptureActivity.class);
			this.startActivityForResult(intent, IDef.Req_Code_Camera);
		}
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {

		switch(requestCode) {
			case IDef.Req_Code_Camera: {
				if( (resultCode == Activity.RESULT_OK) && (data != null) ) {
					Bundle bundle = data.getExtras();
					String filePath = bundle.getString(IDef.Extra_File_Path);
					if(filePath!=null) {
						startRecognize(filePath);
					}
				}
				break;
			}
			default: {
				break;
			}
		}

		super.onActivityResult(requestCode, resultCode, data);
	}

	//识别结束
	protected void recognizedFinished(Bundle bundle) {

		mBtnCapture.setVisibility(View.VISIBLE);

		tv.setTextColor(Color.BLACK);
		if(bundle == null) {
			tv.setText("识别失败，请再试");
			return;
		}

		String result = bundle.getString(IDef.Extra_Recog_Result);
		if(result == null) {
			tv.setText("识别失败，请再试");
			return;
		}

		String arr[] = result.split("룺");
		if (arr != null&& arr.length == 2 && arr[1] != null){
			tv.setText(arr[1]);
		}else{
			tv.setText(result);
		}
	}

	//开始识别
	private void startRecognize(String filePath) {
		// TODO Auto-generated method stub
		//Toast.makeText(this, text, Toast.LENGTH_SHORT).show();

		mBtnCapture.setImageBitmap(BitmapFactory.decodeFile(filePath));

		tv.setText("正在识别，请稍候……");
		tv.setTextColor(Color.BLUE);


		RecognizeThread t = new RecognizeThread(this.mMsgHandler, filePath);
		t.start();
	}
};
